package com.weigee.ktv.presenter

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.alibaba.fastjson.JSONArray
import com.linde.library.base.BasePresenter
import com.linde.library.eventbus.EventSendEntity
import com.weigee.ktv.model.WeigeeApi
import com.weigee.ktv.presenter.adapter.rv.SupermarketShoppingCategoryAdapter
import com.weigee.ktv.presenter.adapter.rv.SupermarketShoppingListAdapter
import com.weigee.ktv.model.entities.ShoppingCartEntity
import com.weigee.ktv.model.entities.ShoppingCartListEntity
import com.weigee.ktv.model.entities.SupermarketShoppingCategoryEntity
import com.weigee.ktv.model.entities.ShoppingGoodsEntity
import com.weigee.ktv.model.interfaces.IShoppingCart
import com.weigee.ktv.presenter.adapter.rv.ShoppingCartListAdapter
import com.weigee.ktv.view.interfaces.SupermarketShoppingListView
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * Created by linde on 2017/5/28.
 *<p/>
 */
class SupermarketShoppingListPresenter(private var view: SupermarketShoppingListView?) : BasePresenter(), IShoppingCart {
    private var shopId: Int? = null

    private val cartList = ArrayList<ShoppingCartEntity>()// 购物车
    val cartAdapter = ShoppingCartListAdapter(this)

    val categoryAdapter = SupermarketShoppingCategoryAdapter(this)
    val listAdapter = SupermarketShoppingListAdapter(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        notifyShoppingCartChanged()
    }

    override fun onCheckIntent(intent: Intent?) {
        super.onCheckIntent(intent)
        shopId = intent?.getIntExtra("shopId", 1)
        loadCategory()
    }

    override fun onCheckArguments(arguments: Bundle?) {
        super.onCheckArguments(arguments)
        shopId = arguments?.getInt("shopId", 0)
        loadCategory()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        view = null
    }

    // 载入商品分类数据
    private fun loadCategory() {
        view?.taskPreview()
        WeigeeApi.INSTANCE.service.supermarketShoppingCategory(shopId).enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
                view?.taskCompletely()

                val data = response?.body()?.string()
                if (TextUtils.isEmpty(data)) {
                    view?.onLoadShoppingCategoryErrorData()
                    return
                } else {
                    val list = JSONArray.parseArray(data, SupermarketShoppingCategoryEntity::class.java) as ArrayList<SupermarketShoppingCategoryEntity>?
                    categoryAdapter.mDataList.clear()
                    list?.let {
                        categoryAdapter.mDataList.addAll(it)
                        categoryAdapter.notifyDataSetChanged()
                    }
                    // 刷新商品分类id并加载商品列表
                    loadShoppingList(list?.get(0)?.id)
                }
            }

            override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
                view?.taskCompletely()
                view?.onLoadShoppingCategoryFailure(t)
            }
        })
    }

    private fun loadShoppingList(categoryId: Int?) {
        view?.taskPreview()
        listAdapter.mDataList.clear()
        WeigeeApi.INSTANCE.service.supermarketShoppingList(shopId, categoryId).enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
                view?.taskCompletely()
                val data = response?.body()?.string()
                if (TextUtils.isEmpty(data)) {
                    view?.onLoadShoppingListErrorData()
                    return
                }
                val list = JSONArray.parseArray(data, ShoppingGoodsEntity::class.java) as ArrayList?
                // 刷新商品列表
                list?.let {
                    listAdapter.mDataList.addAll(list)
                    listAdapter.notifyDataSetChanged()
                }
            }

            override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
                view?.taskCompletely()
                view?.onLoadShoppingListFailure()
            }
        })
    }

    fun onSelectedShoppingCategory(eventSendEntity: EventSendEntity?) {
        val categoryId = eventSendEntity?.msg1 as Int?
        loadShoppingList(categoryId)
    }

    override fun getShoppingCartNum(shopId: Int?, categoryId: Int?, shoppingGoodsId: Int?): Int {
        return cartList.count {
            if (shoppingGoodsId == null) {
                shopId ?: this.shopId == it.shopId && categoryId ?: categoryId == it.goods?.categoryId
            } else {
                shopId ?: this.shopId == it.shopId && categoryId ?: categoryId == it.goods?.categoryId && shoppingGoodsId == it.goods?.id
            }
        }
    }

    override fun addToCart(shopId: Int?, entity: ShoppingGoodsEntity?) {
        cartList.add(ShoppingCartEntity(shopId ?: this.shopId, entity))
        notifyShoppingCartChanged()
    }

    override fun removeFromCart(shopId: Int?, categoryId: Int?, shoppingGoodsId: Int?) {
        for (entity in cartList) {
            if (shoppingGoodsId == null) {
                if (shopId ?: this.shopId == entity.shopId && categoryId == entity.goods?.categoryId) {
                    cartList.remove(entity)
                    break
                }
            } else {
                if (shopId ?: this.shopId == entity.shopId && categoryId == entity.goods?.categoryId && shoppingGoodsId == entity.goods?.id) {
                    cartList.remove(entity)
                    break
                }
            }
        }
        notifyShoppingCartChanged()
        if (cartList.isEmpty()) {
            view?.onDismissShoppingCartDetail()
        }
    }

    private fun notifyShoppingCartChanged() {
        var cartNum = 0
        var priseAll = 0F
        for (entity in cartList) {
            if (entity.shopId == shopId) {
                cartNum++
                entity.goods?.price?.let {
                    priseAll += it
                }
            }
        }
        view?.onUpdateShoppingCartNum(cartNum, priseAll)

        categoryAdapter.notifyDataSetChanged()
        listAdapter.notifyDataSetChanged()
        // 刷新购物车列表
        val list = ArrayList<ShoppingCartListEntity>()
        var cartListEntity: ShoppingCartListEntity
        var checked: Boolean
        for (cartEntity in cartList) {
            checked = false
            for (shoppingCartListEntity in list) {
                if (cartEntity.shopId == shoppingCartListEntity.shopId
                        && cartEntity.goods?.categoryId == shoppingCartListEntity.goodsEntity?.categoryId
                        && cartEntity.goods?.id == shoppingCartListEntity.goodsEntity?.id) {

                    shoppingCartListEntity.addCheck()
                    checked = true
                    break
                }
            }
            if (checked) continue
            cartListEntity = ShoppingCartListEntity(cartEntity.shopId, cartEntity.goods)
            list.add(cartListEntity)
        }
        cartAdapter.mDataList.clear()
        cartAdapter.mDataList.addAll(list)
        cartAdapter.notifyDataSetChanged()
    }

    // 清空购物车
    fun clearShoppingCart() {
        cartList.clear()
        notifyShoppingCartChanged()
    }

    // 判断购物车是否为空（如果为空，不可显示购物车详情）
    fun isCanShowShoppingCartDialog(): Boolean {
        return cartList.isNotEmpty()
    }
}